// pages/in_detail_buy/in_detail_buy.js
var app = getApp();//引用app.js
var tuan_id = "";//团购时页面传的id
var istuan = "0";//判断是否是团购
var commonURL = app.data.baseURL;
var commonURLXX = app.data.lastURL;
var commonURLYY = app.data.newURL;
var animation = wx.createAnimation({
  duration: 600,  //动画持续时间，单位ms，默认值 400
  timingFunction: 'linear', //linear  动画一直较为均匀
  success: function (res) {
    //console.log(res)
  }
});
Page({
  data: {
    "BTN": {
      background: "#aaa",
      bindtap: ""
    },
    "yunfei": '0.00',
    // "yunfei_ziti":'0.00',
    // "shiprice_ziti":'0.00',
    "shiprice": '0.00',
    // "xiaojiprice":"0.00",
    "IP": "",
    "display": {
      KD: "block",
      MD: "block",
      SH: "none"
    },
    "hasAdd": "",
    "shippingAdd": {},
    "detail": [],
    "dispatchList": [],
    "currentLX": "小区自提点",
    "peisongFF": "-1",
    "peisongFFDisplay": 'none',
    "chooseAdd": [
      "小区自提点"
      // "小区自提点","快递配送", "送货上门"
      // "收货地址"3,"快递配送"0,"小区自提点"1,"送货上门"2
    ],
    "zitiAdd": {
      txt: "请选择自提地点",
      id: ""
    },
    "zitiName": "",
    "zitiPhone": "",
    "disabledTime": "none",
    "time": {//用户选择后显示在界面的时间
      day: "",
      time: ""
    },
    "day": [
      { name: '今天', value: '今天' },
      { name: '明天', value: '明天' },
      { name: '后天', value: '后天' }
    ],
    "times": [
      // {name: '07:00-09:00', value: '07:00-09:00'}
    ],
    "RemarkValue": "",
    "animation": "",
    "close": "none",//关闭图标属性
    freight_text: ''
  },
  onLoad: function (options) {
    var that = this;
    wx.getStorage({
      key: 'stores',
      success: function (res) {
        console.log(res.data, 8815)
        for (var key in res.data) {
          that.setData({
            zitiAdd: {
              txt: res.data[key].storename,
              id: res.data[key].id
            },
            ZTaddress: res.data[key].address
          })
        }
      },
    })
    options.tuan_id && (tuan_id = options.tuan_id);
    options.istuan = true ? istuan = "1" : istuan = "0";
    wx.getStorage({
      key: 'IP',
      success: function (res) {
        that.setData({ IP: res.data })
      }
    })
    wx.request({
      url: commonURLYY + 'op=cart_view',
      data: {
        openid: app.data.openid || wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        var arr = [];
        var sumprice = 0;
        for (var key in res.data.list) {
          var obj = {};
          obj.id = res.data.list[key].id;
          obj.title = res.data.list[key].title;
          obj.price = res.data.list[key].price;
          obj.num = res.data.list[key].num;
          obj.img = res.data.list[key].img;
          obj.optionname = res.data.list[key].item;
          sumprice += Number(obj.price) * Number(obj.num);
          arr.push(obj);
        }
        that.setData({
          detail: arr,
          xiaojiprice: sumprice.toFixed(2),
          shiprice: sumprice.toFixed(2),
          shiprice_ziti: sumprice.toFixed(2),
        })
      }
    })
    var currentLX = "";
    var areaid = "";
    wx.getStorage({//获取小区地址
      key: 'xiaoqu',
      success: function (res) {
        console.log(res.data.item, "xiaoqu")
        areaid = res.data.item.id
        that.setData({
          region: res.data.item,
          xiaoqudw: res.data.item.name,
          phone: res.data.item.join_hotline,
          phone1: res.data.item.merchant_entry,
        });
        wx.request({
          url: commonURLXX + 'op=uniacid_base',
          data: {
            key: 'base',
            areaid: areaid
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res)
            var deliverytype = res.data.deliverytype;
            //console.log(deliverytype);
            switch (deliverytype) {
              case "1":
                that.setData({ chooseAdd: ["快递配送", "小区自提点"] });
                break;
              case "2":
                that.setData({ chooseAdd: ["快递配送", "送货上门"] });
                break;
              case "3":
                that.setData({
                  chooseAdd: ["小区自提点", "送货上门"],
                  currentLX: "小区自提点"
                });
                break;
              case "4":
                that.setData({ chooseAdd: ["快递配送"] });
                break;
              case "5":
                that.setData({
                  chooseAdd: ["送货上门"],
                  currentLX: "送货上门"
                });
                break;
              case "6":
                that.setData({
                  chooseAdd: ["小区自提点"],
                  currentLX: "小区自提点"
                });
                break;
              case "7":
                that.setData({ chooseAdd: ["快递配送", "小区自提点", "送货上门"] });
                break;
              default:
                that.setData({
                  chooseAdd: ["收货地址"],
                  currentLX: "收货地址"
                });
                break;
            }
            //加载快递
            if (deliverytype == 1 || deliverytype == 2 || deliverytype == 4 || deliverytype == 7) {
              if (res.data.dispatch_list.length > 0) {
                var arr = [];
                for (var key in res.data.dispatch_list) {
                  var obj = {};
                  obj.id = res.data.dispatch_list[key].id;
                  obj.name = res.data.dispatch_list[key].name;
                  arr.push(obj);
                }
                that.setData({
                  "dispatchList": arr
                });
              } else {
                that.setData({
                  peisongFFDisplay: 'none'
                });
              }
            }
            //存储门店
            wx.setStorage({
              key: "stores",
              data: res.data.stores
            })
          },
        })
      }
    })
    //加载默认地址信息,如果没有
    wx.request({
      url: commonURL + 'op=address',
      data: {
        openid: app.data.openid || wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        var hasAdd = "";
        var KD = {};
        if (res.data) {
          hasAdd = true;
          KD = {
            id: res.data.id,
            name: res.data.cname,
            phone: res.data.tel,
            leixing: res.data.type == "1" ? "公司" : "家庭",
            addaa: res.data.province,
            addab: res.data.city,
            addac: res.data.county,
            addb: res.data.detailed_address
          }
        } else {
          hasAdd = false;
        }
        that.setData({
          hasAdd: hasAdd,
          shippingAdd: KD
        })
        wx.setStorage({
          key: 'address',
          data: {
            currentLX: that.data.currentLX,
            hasAdd: hasAdd,
            MD: {
              id: "",
              name: ""
            },
            KD: KD
          }
        })
      }
    })
    wx.getStorage({
      key: 'add',
      success: function (res) {
        console.log(res)
        that.setData({
          zitiName: res.data.addname,
          zitiPhone: res.data.addmobile
        })
      }
    })
  },
  onReady: function () {
    // 页面渲染完成
    this.setData({//页面加载完成后，才可以点击提交订单按钮
      "BTN": {
        background: "#dc6992",
        bindtap: "orderSubmit"
      }
    })
  },
  onShow: function () {
    // 页面显示,地址页返回时更新数据
    var that = this;
    wx.getStorage({
      key: 'stores',
      success: function (res) {
        console.log(res.data, 8815)
        for (var key in res.data) {
          that.setData({
            zitiAdd: {
              txt: res.data[key].storename,
              id: res.data[key].id
            },
            ZTaddress: res.data[key].address
          })
        }
      },
    })
    wx.getStorage({
      key: 'address',
      success: function (res) {
        var options = res.data;
        var currentLX = "";
        if (options.currentLX == "小区自提点") {//如果是自提
          // var address = wx.getStorageSync('address');
          if (!options.freight) {
            options.freight = '0.00'
          }
          var shiprice = (parseFloat(that.data.xiaojiprice) + parseFloat(options.freight)).toFixed(2);
          // var shiprice_ziti = (parseFloat(that.data.xiaojiprice) + parseFloat(options.freight)).toFixed(2);
          that.setData({
            currentLX: "小区自提点",//类型参数，从后一页获取
            zitiAdd: {
              txt: options.MD.name == "" ? "请选择自提地点" : options.MD.name,//自提地点
              id: options.MD.id
            },
            // yunfei_ziti: options.freight,
            yunfei: options.freight,
            shiprice: shiprice
          });
        }else if (options.currentLX == "快递配送" || options.currentLX == "送货上门" || options.currentLX == "收货地址") {//如果是快速配送或者送货上门
          var hasAdd;
          (options.KD.id == "" || !options.KD.id) ? hasAdd = false : hasAdd = true;
          that.setData({
            "currentLX": options.currentLX,
            "hasAdd": hasAdd,//是否选择地点
            freight_text: '请选择快递方式',
            "shippingAdd": {
              id: options.KD.id,
              name: options.KD.name,
              phone: options.KD.phone,
              leixing: options.KD.leixing,
              addaa: options.KD.addaa,
              addab: options.KD.addab,
              addac: options.KD.addac,
              addb: options.KD.addb
            },
            peisongFF: "-1"
          });
        }
      }
    })

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // wx.removeStorageSync('address')
  },
  chooseziti: function (e) {
    this.setData({
      currentAdd: e.currentTarget.dataset.index
    });
  },
  chooseAdd: function (e) {
    var _lxTab = e.currentTarget.dataset.lx;
    if (_lxTab == this.data.currentLX) return;
    var that = this;
    var detail = that.data.detail;
    detail.yunfei = "0.00",
      detail.shiprice = detail.price;
    that.setData({
      //currentLX: e.currentTarget.dataset.index
      currentLX: e.currentTarget.dataset.lx,
      detail: detail,
      peisongFF: "-1",
      yunfei: '0.00',
      shiprice: that.data.xiaojiprice,
      hasAdd: false,
      freight_text: '请选择快递方式',
      zitiAdd: {
        txt: '请选择自提地点',
        id: ''
      }
    });
  },
  choosePSFF: function (e) {//选择配送方式
    var that = this;
    var index = e.currentTarget.dataset.index;
    var Lists = that.data.dispatchList;
    var tid = Lists[index].id;
    var freight_text = this.data.dispatchList[index].name;
    if (that.data.shippingAdd.addaa == "" || that.data.shippingAdd.addab == "" || that.data.shippingAdd.addac == "") {
      wx.showToast({
        title: '请先选择收货地址',
        icon: 'loading',
        duration: 3000
      })
      this.setData({
        peisongFFDisplay: 'none'
      })
    } else {
      wx.request({//加载运费,配送方式
        url: 'https://min.lexiangpingou.cn/min_cart_api.php?op=freight',
        data: {
          tid: tid,
          uniacid: app.data.GZHid,
          openid: app.data.openid,
          province: that.data.shippingAdd.addaa,
          city: that.data.shippingAdd.addab,
          county: that.data.shippingAdd.addac
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (!res.data) {
            return false
          }
          var freight = parseFloat(res.data.freight) || 0;
          var yunfei = freight.toFixed(2);
          var shiprice = (parseFloat(that.data.xiaojiprice) + parseFloat(freight)).toFixed(2);
          that.setData({
            yunfei: yunfei,
            shiprice: shiprice,
            peisongFFDisplay: 'none',
            freight_text: freight_text
          })
        }
      })
      that.setData({
        peisongFF: index
      });
    }
  },
  closeTime: function () {
    var that = this;
    if (this.data.time.day != "" && this.data.time.time != "") {
      animation.height("0").step();
      this.setData({
        animation: animation.export() //输出动画
      })
      setTimeout(function () {
        that.setData({ disabledTime: "none" });
      }, 600)
    } else {
      wx.showToast({
        title: '请选择送货时间',
        duration: 2000
      })
    }
  },
  openTime: function () {//选择送货时间
    this.setData({
      disabledTime: "block"
    });
    animation.height("540rpx").step();
    this.setData({
      animation: animation.export()//输出动画
    })
  },
  open: function (e) {
    //查看拼团详情,拼团
    this.setData({
      close: "block"
    })
  },
  close: function (e) {
    //关闭拼团详情
    this.setData({
      close: "none"
    })
  },
  radioChangeDay: function (e) {
    //选择送货日期
    var that = this;
    wx.request({//动态加载时间
      url: commonURL + 'op=xcxsendtime',
      data: {
        ad: e.detail.value,
        is_tuan: 0,
        openid: app.data.openid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res, 456456)
        if (!res.data) {
          return false
        }
        that.setData({
          "times": res.data.ttime,
          "time": {
            day: e.detail.value,
            time: ""
          },
          yunfei: (Number(res.data.cost)).toFixed(2),
          shiprice: (Number(that.data.shiprice) + Number(res.data.cost)).toFixed(2),
        });
      }
    })
  },
  radioChangeTime: function (e) {
    //选择送货时间段
    this.setData({
      "time.time": e.detail.value
    });
  },
  chooseCoupons: function () {
    //选择优惠券，跳转前先判断，若无优惠券则不跳转
    wx.showToast({
      title: '暂无可用优惠券',
      icon: 'loading',
      duration: 1500
    })
  },
  bindKeyInputName: function (e) {
    this.setData({
      zitiName: e.detail.value
    })
  },
  bindKeyInputPhone: function (e) {
    this.setData({
      zitiPhone: e.detail.value
    })
  },
  gotoAddress: function (e) {
    var that = this;
    wx.getStorage({
      key: 'address',
      success: function (res) {
        var address = res.data;
        console.log(e.currentTarget.dataset.type)
        address.currentLX = that.data.currentLX;//更改缓存的currentLX的值，防止返回后页面data与缓存数据不同的bug
        wx.setStorage({
          key: 'address',
          data: address,
          success: function (res) {
            wx.navigateTo({
              url: '../index_add/index_add?addressChoose=' + e.currentTarget.dataset.type,
            })
          }
        })
      }
    })
  },
  orderSubmit: function (e) {
    var that = this;
    var formid = e.detail.formId;
    //下单前判断必填信息是否填写完成
    var addressid = "", addresstype = "", comadd = "", addname = "", mobile = "", address = "", senddate = "",
      sendtime = "", dispatchtype = "";
    if (that.data.currentLX == "小区自提点") {
      dispatchtype = "3";
      if (!that.data.zitiAdd.id) {//判断是否填写自提地点
        wx.showToast({
          title: '请选择自提地点',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
      if (!that.data.zitiName) {
        wx.showToast({
          title: '请填写收货人',
          icon: 'loading',
          duration: 1500
        })
        return false;
      } else {
        wx.setStorage({
          key: 'add',
          data: {
            addmobile: that.data.zitiPhone,
            addname: that.data.zitiName
          },
        })
      }
      if (!that.data.zitiPhone) {
        wx.showToast({
          title: '请填写联系电话',
          icon: 'loading',
          duration: 1500
        })
        return false;
      } else if (!(/^1[34578]\d{9}$/.test(that.data.zitiPhone))) {
        wx.showToast({
          title: '联系电话填写有误，请重新填写',
          icon: 'loading',
          duration: 2000
        })
        return false;
      }
      comadd = that.data.zitiAdd.id;
      addname = that.data.zitiName;//收货人
      mobile = that.data.zitiPhone;//收货电话
      address = that.data.zitiAdd.txt;
    }else if (that.data.currentLX == "快递配送" || that.data.currentLX == "收货地址") {
      if (!that.data.shippingAdd.id) {//判断是否填写收货地址
        wx.showToast({
          title: '请填写收货地址',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
      if (that.data.peisongFF == "-1") {
        if (that.data.peisongFF == '-1') {
          wx.showToast({
            title: '请选择快递方式',
            icon: 'loading',
            duration: 1500
          })
          return false;
        }
      }
      if (that.data.peisongFFDisplay != 'none') {
        comadd = that.data.dispatchList[that.data.peisongFF].id;
      }
      dispatchtype = "2";
      addressid = that.data.shippingAdd.id;
      addresstype = that.data.shippingAdd.leixing;
      addname = that.data.shippingAdd.name;
      mobile = that.data.shippingAdd.phone;
      address = that.data.shippingAdd.addaa + that.data.shippingAdd.addab + that.data.shippingAdd.addac + that.data.shippingAdd.addb;
    }else if (that.data.currentLX == "送货上门") {
      dispatchtype = "1";
      if (!that.data.shippingAdd.id) {//判断是否填写收货地址
        wx.showToast({
          title: '请填写收货地址',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
      if (!that.data.time.day || !that.data.time.time) {
        wx.showToast({
          title: '请选择送货时间',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
      addressid = that.data.shippingAdd.id;
      addresstype = that.data.shippingAdd.leixing;
      addname = that.data.shippingAdd.name;
      mobile = that.data.shippingAdd.phone;
      // address = that.data.shippingAdd.addaa + that.data.shippingAdd.addab + that.data.shippingAdd.addac + that.data.shippingAdd.addb;
      address = that.data.zitiAdd.txt;
      senddate = that.data.time.day;
      senddate = that.data.time.time;
    }
    wx.getStorage({//获取小区地址
      key: 'xiaoqu',
      success: function (res) {
        var out_trade_no = "XCX" + Date.parse(new Date()) / 1000 + that.createRand();//订单号，'XCX+时间戳+5位随机数字'
        // var yunfei = that.data.currentLX == '小区自提点' ? that.data.yunfei_ziti : that.data.yunfei;
        // var pay_price = that.data.currentLX == '小区自提点' ? that.data.shiprice_ziti : that.data.shiprice;
        var dataPay = {
          'areaid': res.data.item.id,
          'uniacid': app.data.GZHid,//     => $_GPC['uniacid'],//公众号ID
          'openid': app.data.openid,//      => $_GPC['openid'],//openid
          'orderno': out_trade_no,//     => $_GPC['orderno'],//订单编号
          'is_hexiao': that.data.currentLX == '小区自提点' ? 1 : 0,
          'pay_price': that.data.shiprice,//   => $_GPC['pay_price'],//支付金额（商品金额+运费-优惠金额-团长优惠）
          'freight': that.data.yunfei,//     => $_GPC['freight'],//运费
          'firstdiscount': "",//   => $_GPC['firstdiscount'],//团长优惠
          'addressid': addressid,//   => $_GPC['addressid'],
          'addresstype': addresstype,// => $_GPC['addresstype'],//1公司2家庭
          'dispatchtype': dispatchtype,//=> $_GPC['dispatchtype'],//配送方式
          'store_id': comadd,//      =>$_GPC['store_id'],//
          'cname': addname,//     => $_GPC['cname'], 选择小区自提点时的名字
          'tel': mobile,//      => $_GPC['tel'],  选择小区自提点时的手机号
          'province': that.data.shippingAdd.addaa,
          'city': that.data.shippingAdd.addab,
          'county': that.data.shippingAdd.addac,
          // 'address': that.data.shippingAdd.addb,//     => $_GPC['province'].$_GPC['city'].$_GPC['county'].$_GPC['detailed_address'],
          'address': address,
          'tuan_id': '',//     => $_GPC['tuan_id'],
          'is_tuan': 0,//     => $_GPC['is_tuan'],//拼团为1，其它类型为0
          'senddate': senddate,//    => $_GPC['senddate'],//送货日期
          'sendtime': sendtime,//    =>$_GPC['sendtime'],//送货时间
          'remark': that.data.RemarkValue,//      => $_GPC['remark'],//订单备注
          'couponid': "",//    => $_GPC['$couponid'],//优惠券ID
          'is_usecard': "0",//  => $_GPC['is_usecard'],//使用优惠券为1，不使用为0
          'discount_fee': "",//=> $_GPC['discount_fee'],//优惠券优惠金额
          'transid': out_trade_no //订单号
        }
        wx.request({//下单前先传数据给后台，后台先建立订单
          url: commonURLXX + 'op=order_confirm',
          data: dataPay,
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            if (res.data.status != "1") {
              wx.showToast({
                title: '订单生成失败,请检查网络或重新提交',
                icon: 'loading',
                duration: 4000
              })
            } else {
              that.payModal(out_trade_no, that);//弹出订单支付模态框
            }
            that.setData({
              isSubmit: true,
              formid: formid,
            })
          }
        })
      }
    })

  },
  payModal: function (out_trade_no, that) {
    wx.getStorage({
      key: 'IP',
      success: function (res) {
        that.setData({ IP: res.data })
      }
    })
    wx.showLoading({
      title: '正在加载...',
    })
    var total_fee = parseFloat(that.data.shiprice) * 100;//总价格,以分为单位，不能有小数点
    var nonce_str = that.createNonceStr();
    //MD5加密代码
    var stringA = "appid=" + app.data.appid + "&body=" + app.data.body + that.data.detail[0].title + "&mch_id=" + app.data.mch_id + "&nonce_str=" + nonce_str + "&notify_url=" + "https://min.lexiangpingou.cn/payment/wechat/notify.php" + "&openid=" + app.data.openid + "&out_trade_no=" + out_trade_no + "&spbill_create_ip=" + that.data.IP + "&total_fee=" + total_fee.toFixed(0) + "&trade_type=" + "JSAPI";
    var stringSignTemp = stringA + "&key=" + app.data.paykey;
    var sign = "";
    sign = that.MD5(stringSignTemp);
    var formData = "<xml>"
    formData += "<appid>" + app.data.appid + "</appid>" //appid
    formData += "<mch_id>" + app.data.mch_id + "</mch_id>" //商户号 attach
    formData += "<body>" + app.data.body + that.data.detail[0].title + "</body>"
    formData += "<nonce_str>" + nonce_str + "</nonce_str>" //随机字符串，不长于32位。
    formData += "<notify_url>" + "https://min.lexiangpingou.cn/payment/wechat/notify.php" + "</notify_url>"
    formData += "<openid>" + app.data.openid + "</openid>"
    formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>"
    formData += "<spbill_create_ip>" + that.data.IP + "</spbill_create_ip>"
    formData += "<total_fee>" + total_fee.toFixed(0) + "</total_fee>"
    formData += "<trade_type>JSAPI</trade_type>"
    formData += "<sign>" + sign + "</sign>"
    formData += "</xml>"
    wx.request({//微信统一下单接口------------
      url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
      method: "POST",
      data: formData,
      header: {
        'content-type': 'application/json'
      },
      "success": function (res) {
        console.log(res.data);
        var data = res.data;
        var timeStamp = Date.parse(new Date()) / 1000 + '';
        var nonceStr = that.split(data, "nonce_str");
        var prepay_id = that.split(data, "prepay_id");
        //MD5加密
        var stringB = "appId=" + app.data.appid + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id + "&signType=" + 'MD5' + "&timeStamp=" + timeStamp;
        var stringSignTempB = stringB + "&key=" + app.data.paykey;
        var paySign = that.MD5(stringSignTempB);
        wx.hideLoading();
        wx.requestPayment({//发起微信支付接口-------------
          'timeStamp': timeStamp,
          'nonceStr': nonceStr,
          'package': 'prepay_id=' + prepay_id,
          'signType': 'MD5',
          'paySign': paySign,
          'success': function (res) {
            wx.showModal({
              title: '提示',
              content: '支付成功',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  that.orderquery(out_trade_no, that);//获取微信支付订单号并发送给后台
                } else {
                  that.orderquery(out_trade_no, that);//获取微信支付订单号并发送给后台
                }
              }
            })
          },
          'fail': function (res) {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '支付失败,请稍后重新下单',
              complete: function (res) {
                wx.redirectTo({
                  url: '../myorder/myorder',
                })
              }
            })
          }
        })
      },
      'fail': function (res) {
        console.log(res);
        wx.showToast({
          title: '下单失败',
          icon: 'loading',
          duration: 2000
        })
        setTimeout(function () {
          wx.redirectTo({
            //小程序里面navigateTo与redirectTo不能跳转到tabBar页面
            url: '../myorder/myorder'
          })
        }, 4000)
      }
    })
    //提交订单,弹出模态框
    // wx.showModal({
    //   title: '订单已生成，确认支付？',
    //   success: function (res) {
    //     if (res.confirm) {
    //       wx.getStorage({
    //         key: 'IP',
    //         success: function (res) {
    //           that.setData({ IP: res.data })
    //         }
    //       })
    //       // var pay_price = that.data.currentLX == '小区自提点' ? that.data.shiprice_ziti : that.data.shiprice;
    //       var total_fee = parseFloat(that.data.shiprice) * 100;//总价格,以分为单位，不能有小数点
    //       // var total_fee=parseFloat(that.data.shiprice)*100;//总价格,以分为单位，不能有小数点
    //       var nonce_str = that.createNonceStr();
    //       //MD5加密代码
    //       var stringA = "appid=" + app.data.appid + "&body=" + app.data.body + that.data.detail[0].title + "&mch_id=" + app.data.mch_id + "&nonce_str=" + nonce_str + "&notify_url=" + "https://min.lexiangpingou.cn/payment/wechat/notify.php" + "&openid=" + app.data.openid + "&out_trade_no=" + out_trade_no + "&spbill_create_ip=" + that.data.IP + "&total_fee=" + total_fee.toFixed(0) + "&trade_type=" + "JSAPI";
    //       var stringSignTemp = stringA + "&key=" + app.data.paykey;
    //       var sign = "";
    //       sign = that.MD5(stringSignTemp);
    //       var formData = "<xml>"
    //       formData += "<appid>" + app.data.appid + "</appid>" //appid
    //       formData += "<mch_id>" + app.data.mch_id + "</mch_id>" //商户号 attach
    //       formData += "<body>" + app.data.body + that.data.detail[0].title + "</body>"
    //       formData += "<nonce_str>" + nonce_str + "</nonce_str>" //随机字符串，不长于32位。
    //       formData += "<notify_url>" + "https://min.lexiangpingou.cn/payment/wechat/notify.php" + "</notify_url>"
    //       formData += "<openid>" + app.data.openid + "</openid>"
    //       formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>"
    //       formData += "<spbill_create_ip>" + that.data.IP + "</spbill_create_ip>"
    //       formData += "<total_fee>" + total_fee.toFixed(0) + "</total_fee>"
    //       formData += "<trade_type>JSAPI</trade_type>"
    //       formData += "<sign>" + sign + "</sign>"
    //       formData += "</xml>"
    //       wx.request({//微信统一下单接口------------
    //         url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
    //         method: "POST",
    //         data: formData,
    //         header: {
    //           'content-type': 'application/json'
    //         },
    //         "success": function (res) {
    //           console.log(res.data);
    //           var data = res.data;
    //           var timeStamp = Date.parse(new Date()) / 1000 + '';
    //           var nonceStr = that.split(data, "nonce_str");
    //           var prepay_id = that.split(data, "prepay_id");
    //           //MD5加密
    //           var stringB = "appId=" + app.data.appid + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id + "&signType=" + 'MD5' + "&timeStamp=" + timeStamp;
    //           var stringSignTempB = stringB + "&key=" + app.data.paykey;
    //           var paySign = that.MD5(stringSignTempB);

    //           wx.requestPayment({//发起微信支付接口-------------
    //             'timeStamp': timeStamp,
    //             'nonceStr': nonceStr,
    //             'package': 'prepay_id=' + prepay_id,
    //             'signType': 'MD5',
    //             'paySign': paySign,
    //             'success': function (res) {
    //               wx.showModal({
    //                 title: '提示',
    //                 content: '支付成功',
    //                 showCancel: false,
    //                 success: function (res) {
    //                   if (res.confirm) {
    //                     that.orderquery(out_trade_no, that);//获取微信支付订单号并发送给后台
    //                   } else {
    //                     that.orderquery(out_trade_no, that);//获取微信支付订单号并发送给后台
    //                   }
    //                 }
    //               })
    //             },
    //             'fail': function (res) {
    //               wx.showModal({
    //                 title: '提示',
    //                 showCancel: false,
    //                 content: '支付失败,请在订单页面继续完成支付',
    //                 complete: function (res) {
    //                   wx.redirectTo({
    //                     url: '../myorder/myorder',
    //                   })
    //                 }
    //               })
    //             }
    //           })
    //         },
    //         'fail': function (res) {
    //           console.log(res);
    //           wx.showToast({
    //             title: '下单失败',
    //             icon: 'loading',
    //             duration: 2000
    //           })
    //           setTimeout(function () {
    //             wx.redirectTo({
    //               //小程序里面navigateTo与redirectTo不能跳转到tabBar页面
    //               url: '../myorder/myorder'
    //             })
    //           }, 4000)
    //         }
    //       })
    //     } else {
    //       wx.switchTab({
    //         url: '../index/index'
    //       })
    //     }
    //   }
    // })
  },
  orderquery: function (out_trade_no, that) {//查询订单，把“微信支付订单号”发给后台
    var nonce_str = that.createNonceStr();
    //MD5加密代码
    var stringA = "appid=" + app.data.appid + "&mch_id=" + app.data.mch_id + "&nonce_str=" + nonce_str + "&out_trade_no=" + out_trade_no;
    var stringSignTemp = stringA + "&key=" + app.data.paykey;
    var sign = that.MD5(stringSignTemp);
    var dataxml = "<xml><appid>" + app.data.appid + "</appid><mch_id>" + app.data.mch_id + "</mch_id><nonce_str>" + nonce_str + "</nonce_str><out_trade_no>" + out_trade_no + "</out_trade_no><sign>" + sign + "</sign></xml>";
    wx.request({
      url: 'https://api.mch.weixin.qq.com/pay/orderquery', //商户可以通过查询订单接口主动查询订单状态，完成下一步的业务逻辑。
      data: dataxml,
      method: "POST",
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        var transaction_id = that.split(res.data, "transaction_id");
        var total_fee = parseInt(data.split("<total_fee>")[1].split("</total_fee>")) / 100;
        wx.request({
          url: commonURLXX + 'op=check_payresult',
          data: {
            orderno: out_trade_no,    //商品订单号
            transid: transaction_id,
            fee: total_fee,
            form_id: that.data.formid,
            appid: app.data.appid,
            secret: app.data.secret
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res.data);
            if (res.data.status != "1") {
              return false;
            }
            if (!res.data.tuan_id) {//判断是否是团购，跳转订单详情
              wx.redirectTo({ url: '../myorder_detail/myorder_detail?orderid=' + res.data.order_id });
            } else {//跳转团详情
              wx.redirectTo({ url: '../mygroup_detail/mygroup_detail?goodsid=' + res.data.order_id + '&tuan_id=' + res.data.tuan_id });
            }
          }
        })
      }
    })
  },
  bindRemarkInput: function (e) {
    this.setData({
      RemarkValue: e.detail.value
    })
  },
  updataSaleNum: function (that) {
    wx.getStorage({//加载数据，更改缓存中的该商品的库存
      key: 'indexLists',
      success: function (res) {
        var id = that.data.detail.id;
        console.log(id);
        if (id) {
          var indexLists = res;
          wx.request({//ajax加载商品详情
            url: commonURL + 'op=goods_detail',
            data: {
              id: id
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              indexLists.id.salenum = res.salenum;
              wx.setData({ indexLists: indexLists })
            }
          })
        }
      }
    })
  },
  createNonceStr: function () {
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < 32; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd
  },
  createRand: function () {//产生5位随机数字，用于拼接订单号
    var chars = '0123456789';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < 4; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd
  },
  split: function (xml, node_name) {
    var tmp = xml.split("<" + node_name + ">")
    var _tmp = tmp[1].split("</" + node_name + ">")
    return _tmp[0].split("<![CDATA[")[1].split("]]")[0]
  },
  MD5: function (a) {//MD5加密代码
    var hexcase = 1;
    var mmdd = rstr2hex(rstr_md5(str2rstr_utf8(a)));
    return mmdd;

    function hex_hmac_md5(a, b) {
      return rstr2hex(rstr_hmac_md5(str2rstr_utf8(a), str2rstr_utf8(b)))
    }

    function md5_vm_test() {
      return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72"
    }

    function rstr_md5(a) {
      return binl2rstr(binl_md5(rstr2binl(a), a.length * 8))
    }

    function rstr_hmac_md5(c, f) {
      var e = rstr2binl(c);
      if (e.length > 16) {
        e = binl_md5(e, c.length * 8)
      }
      var a = Array(16), d = Array(16);
      for (var b = 0; b < 16; b++) {
        a[b] = e[b] ^ 909522486;
        d[b] = e[b] ^ 1549556828
      }
      var g = binl_md5(a.concat(rstr2binl(f)), 512 + f.length * 8);
      return binl2rstr(binl_md5(d.concat(g), 512 + 128))
    }

    function rstr2hex(c) {
      try {
        hexcase
      } catch (g) {
        hexcase = 0
      }
      var f = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
      var b = "";
      var a;
      for (var d = 0; d < c.length; d++) {
        a = c.charCodeAt(d);
        b += f.charAt((a >>> 4) & 15) + f.charAt(a & 15)
      }
      return b
    }

    function str2rstr_utf8(c) {
      var b = "";
      var d = -1;
      var a, e;
      while (++d < c.length) {
        a = c.charCodeAt(d);
        e = d + 1 < c.length ? c.charCodeAt(d + 1) : 0;
        if (55296 <= a && a <= 56319 && 56320 <= e && e <= 57343) {
          a = 65536 + ((a & 1023) << 10) + (e & 1023);
          d++
        }
        if (a <= 127) {
          b += String.fromCharCode(a)
        } else {
          if (a <= 2047) {
            b += String.fromCharCode(192 | ((a >>> 6) & 31), 128 | (a & 63))
          } else {
            if (a <= 65535) {
              b += String.fromCharCode(224 | ((a >>> 12) & 15), 128 | ((a >>> 6) & 63), 128 | (a & 63))
            } else {
              if (a <= 2097151) {
                b += String.fromCharCode(240 | ((a >>> 18) & 7), 128 | ((a >>> 12) & 63), 128 | ((a >>> 6) & 63), 128 | (a & 63))
              }
            }
          }
        }
      }
      return b
    }

    function rstr2binl(b) {
      var a = Array(b.length >> 2);
      for (var c = 0; c < a.length; c++) {
        a[c] = 0
      }
      for (var c = 0; c < b.length * 8; c += 8) {
        a[c >> 5] |= (b.charCodeAt(c / 8) & 255) << (c % 32)
      }
      return a
    }

    function binl2rstr(b) {
      var a = "";
      for (var c = 0; c < b.length * 32; c += 8) {
        a += String.fromCharCode((b[c >> 5] >>> (c % 32)) & 255)
      }
      return a
    }

    function binl_md5(p, k) {
      p[k >> 5] |= 128 << ((k) % 32);
      p[(((k + 64) >>> 9) << 4) + 14] = k;
      var o = 1732584193;
      var n = -271733879;
      var m = -1732584194;
      var l = 271733878;
      for (var g = 0; g < p.length; g += 16) {
        var j = o;
        var h = n;
        var f = m;
        var e = l;
        o = md5_ff(o, n, m, l, p[g + 0], 7, -680876936);
        l = md5_ff(l, o, n, m, p[g + 1], 12, -389564586);
        m = md5_ff(m, l, o, n, p[g + 2], 17, 606105819);
        n = md5_ff(n, m, l, o, p[g + 3], 22, -1044525330);
        o = md5_ff(o, n, m, l, p[g + 4], 7, -176418897);
        l = md5_ff(l, o, n, m, p[g + 5], 12, 1200080426);
        m = md5_ff(m, l, o, n, p[g + 6], 17, -1473231341);
        n = md5_ff(n, m, l, o, p[g + 7], 22, -45705983);
        o = md5_ff(o, n, m, l, p[g + 8], 7, 1770035416);
        l = md5_ff(l, o, n, m, p[g + 9], 12, -1958414417);
        m = md5_ff(m, l, o, n, p[g + 10], 17, -42063);
        n = md5_ff(n, m, l, o, p[g + 11], 22, -1990404162);
        o = md5_ff(o, n, m, l, p[g + 12], 7, 1804603682);
        l = md5_ff(l, o, n, m, p[g + 13], 12, -40341101);
        m = md5_ff(m, l, o, n, p[g + 14], 17, -1502002290);
        n = md5_ff(n, m, l, o, p[g + 15], 22, 1236535329);
        o = md5_gg(o, n, m, l, p[g + 1], 5, -165796510);
        l = md5_gg(l, o, n, m, p[g + 6], 9, -1069501632);
        m = md5_gg(m, l, o, n, p[g + 11], 14, 643717713);
        n = md5_gg(n, m, l, o, p[g + 0], 20, -373897302);
        o = md5_gg(o, n, m, l, p[g + 5], 5, -701558691);
        l = md5_gg(l, o, n, m, p[g + 10], 9, 38016083);
        m = md5_gg(m, l, o, n, p[g + 15], 14, -660478335);
        n = md5_gg(n, m, l, o, p[g + 4], 20, -405537848);
        o = md5_gg(o, n, m, l, p[g + 9], 5, 568446438);
        l = md5_gg(l, o, n, m, p[g + 14], 9, -1019803690);
        m = md5_gg(m, l, o, n, p[g + 3], 14, -187363961);
        n = md5_gg(n, m, l, o, p[g + 8], 20, 1163531501);
        o = md5_gg(o, n, m, l, p[g + 13], 5, -1444681467);
        l = md5_gg(l, o, n, m, p[g + 2], 9, -51403784);
        m = md5_gg(m, l, o, n, p[g + 7], 14, 1735328473);
        n = md5_gg(n, m, l, o, p[g + 12], 20, -1926607734);
        o = md5_hh(o, n, m, l, p[g + 5], 4, -378558);
        l = md5_hh(l, o, n, m, p[g + 8], 11, -2022574463);
        m = md5_hh(m, l, o, n, p[g + 11], 16, 1839030562);
        n = md5_hh(n, m, l, o, p[g + 14], 23, -35309556);
        o = md5_hh(o, n, m, l, p[g + 1], 4, -1530992060);
        l = md5_hh(l, o, n, m, p[g + 4], 11, 1272893353);
        m = md5_hh(m, l, o, n, p[g + 7], 16, -155497632);
        n = md5_hh(n, m, l, o, p[g + 10], 23, -1094730640);
        o = md5_hh(o, n, m, l, p[g + 13], 4, 681279174);
        l = md5_hh(l, o, n, m, p[g + 0], 11, -358537222);
        m = md5_hh(m, l, o, n, p[g + 3], 16, -722521979);
        n = md5_hh(n, m, l, o, p[g + 6], 23, 76029189);
        o = md5_hh(o, n, m, l, p[g + 9], 4, -640364487);
        l = md5_hh(l, o, n, m, p[g + 12], 11, -421815835);
        m = md5_hh(m, l, o, n, p[g + 15], 16, 530742520);
        n = md5_hh(n, m, l, o, p[g + 2], 23, -995338651);
        o = md5_ii(o, n, m, l, p[g + 0], 6, -198630844);
        l = md5_ii(l, o, n, m, p[g + 7], 10, 1126891415);
        m = md5_ii(m, l, o, n, p[g + 14], 15, -1416354905);
        n = md5_ii(n, m, l, o, p[g + 5], 21, -57434055);
        o = md5_ii(o, n, m, l, p[g + 12], 6, 1700485571);
        l = md5_ii(l, o, n, m, p[g + 3], 10, -1894986606);
        m = md5_ii(m, l, o, n, p[g + 10], 15, -1051523);
        n = md5_ii(n, m, l, o, p[g + 1], 21, -2054922799);
        o = md5_ii(o, n, m, l, p[g + 8], 6, 1873313359);
        l = md5_ii(l, o, n, m, p[g + 15], 10, -30611744);
        m = md5_ii(m, l, o, n, p[g + 6], 15, -1560198380);
        n = md5_ii(n, m, l, o, p[g + 13], 21, 1309151649);
        o = md5_ii(o, n, m, l, p[g + 4], 6, -145523070);
        l = md5_ii(l, o, n, m, p[g + 11], 10, -1120210379);
        m = md5_ii(m, l, o, n, p[g + 2], 15, 718787259);
        n = md5_ii(n, m, l, o, p[g + 9], 21, -343485551);
        o = safe_add(o, j);
        n = safe_add(n, h);
        m = safe_add(m, f);
        l = safe_add(l, e)
      }
      return Array(o, n, m, l)
    }

    function md5_cmn(h, e, d, c, g, f) {
      return safe_add(bit_rol(safe_add(safe_add(e, h), safe_add(c, f)), g), d)
    }

    function md5_ff(g, f, k, j, e, i, h) {
      return md5_cmn((f & k) | ((~f) & j), g, f, e, i, h)
    }

    function md5_gg(g, f, k, j, e, i, h) {
      return md5_cmn((f & j) | (k & (~j)), g, f, e, i, h)
    }

    function md5_hh(g, f, k, j, e, i, h) {
      return md5_cmn(f ^ k ^ j, g, f, e, i, h)
    }

    function md5_ii(g, f, k, j, e, i, h) {
      return md5_cmn(k ^ (f | (~j)), g, f, e, i, h)
    }

    function safe_add(a, d) {
      var c = (a & 65535) + (d & 65535);
      var b = (a >> 16) + (d >> 16) + (c >> 16);
      return (b << 16) | (c & 65535)
    }

    function bit_rol(a, b) {
      return (a << b) | (a >>> (32 - b))
    };

  },
  onchoose_show: function () {
    var that = this;
    if (that.data.shippingAdd.addaa == "" || that.data.shippingAdd.addab == "" || that.data.shippingAdd.addac == "") {
      wx.showToast({
        title: '请先选择收货地址',
        icon: 'loading',
        duration: 3000
      })
      this.setData({
        peisongFFDisplay: 'none'
      })
    } else {
      this.setData({
        peisongFFDisplay: 'block'
      })
    }
  }
})